package com.xiaoze.transform;

import com.xiaoze.entity.SensorReading;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * TransfromRichFunction
 *
 * @author Lin Zemin
 * @date 2021-12-29
 */
public class TransformRichFunction {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        String path = System.getProperty("user.dir") + "\\src\\main\\resources\\sensor.txt";
        DataStreamSource<String> inputStream = env.readTextFile(path);

        SingleOutputStreamOperator<SensorReading> dataStream = inputStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });

        SingleOutputStreamOperator<Tuple3<String, Integer, Double>> richMapStream = dataStream.map(new MyRichMap());

        richMapStream.print("Rich");

        env.execute();

    }

    public static class MyRichMap extends RichMapFunction<SensorReading, Tuple3<String, Integer, Double>> {

        private static final long serialVersionUID = -4522227948657881724L;

        @Override
        public Tuple3<String, Integer, Double> map(SensorReading sensorReading) throws Exception {
            return new Tuple3<>(sensorReading.getId(), getRuntimeContext().getIndexOfThisSubtask(), sensorReading.getTemperature());
        }

        @Override
        public void open(Configuration parameters) {
            // 初始化工作，一般是定义状态，或者建立数据库连接
            System.out.println("open");
        }

        @Override
        public void close() {
            // 关闭连接和清空状态的收尾工作
            System.out.println("close");
        }

    }

}
